<template>
<div class="container-fluid">
    <div class="box box-primary">
        <div class="box-header">
            <h4 class="text-primary text-center">通道配置</h4>
        </div>
        <div class="box-body">
            <div class="form-inline" autocomplete="off" spellcheck="false">
                <div class="form-group form-group-sm">
                    <label>搜索</label>
                    <div class="input-group input-group-sm" v-if="!isMobile() && hasAnyRole(serverInfo, userInfo, '超级管理员')">
                        <input type="text" ref="search" class="form-control" placeholder="关键字" v-model.trim="q" @keydown.enter.prevent>
                        <div class="input-group-btn">
                            <button type="button" class="btn btn-primary btn-sm" @click.prevent="download" title="下载配置数据"><i class="fa fa-download"></i></button>
                            <button type="button" class="btn btn-primary btn-sm" @click.prevent="$refs['uploadDlg'].show()" title="导入配置数据"><i class="fa fa-upload"></i></button>
                        </div>
                    </div>
                    <input type="text" ref="search" class="form-control" placeholder="关键字" v-model.trim="q" @keydown.enter.prevent v-else>
                </div>
                <span class="hidden-xs">&nbsp;&nbsp;</span>
                <div class="form-group form-group-sm">
                    <label>开启状态</label>
                    <select class="form-control" v-model.trim="enable">
                        <option value="">全部</option>
                        <option value="1">开启</option>
                        <option value="0">关闭</option>
                    </select>
                </div>
                <span class="hidden-xs">&nbsp;&nbsp;</span>
                <div class="form-group form-group-sm">
                    <label>接入类型</label>
                    <select class="form-control" v-model.trim="protocol">
                        <option value="">全部</option>
                        <option value="RTSP">RTSP</option>
                        <option value="ONVIF">ONVIF</option>
                        <option value="RTMP">RTMP</option>
                        <option value="FLV">FLV</option>
                        <option value="HLS">HLS</option>
                        <option value="HIKSDK">海康SDK</option>
                        <option value="DHSDK">大华SDK</option>
                        <option value="TDYSDK">天地伟业SDK</option>
                        <option value="FILE">视频文件</option>
                    </select>
                </div>
                <span class="hidden-xs">&nbsp;&nbsp;</span>
                <div class="form-group form-group-sm">
                    <label>展示方式</label>
                    <select class="form-control" @change="modeChange" :value="mode">
                        <option value="list">列表展示</option>
                        <option value="block">模块展示</option>
                    </select>
                </div>
            </div>
            <div class="clearfix"></div>
            <br>
            <ChannelDlg ref="channelDlg" @submit="getchannels"></ChannelDlg>
            <div v-if="mode == 'list'">
                <el-table :data="Channels" stripe class="view-list" :default-sort="{prop: 'Channel', order: 'ascending'}" @sort-change="sortChange">
                    <el-table-column prop="Channel" :fixed="!isMobile()" label="通道号" center min-width="90" show-overflow-tooltip sortable="custom"></el-table-column>
                    <el-table-column prop="Name" :fixed="!isMobile()" label="通道名称" center min-width="120" show-overflow-tooltip sortable="custom"></el-table-column>
                    <el-table-column prop="Enable" :fixed="!isMobile()" label="是否开启" min-width="120" sortable="custom">
                        <template slot-scope="scope">
                            <el-switch v-model="scope.row.Enable" :active-value="1" :inactive-value="0" @change="enableChannel(scope.row)" :title="scope.row.Enable ? '通道开启':'通道关闭'"></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" min-width="100" :fixed="isMobile() ? false : 'right'">
                        <template slot-scope="scope">
                            <div class="btn-group">
                                <a role="button" class="btn btn-xs btn-info" @click.prevent="editChannel(scope.row)"><i class="fa fa-edit"></i> 编辑</a>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="Protocol" label="接入类型" min-width="120" show-overflow-tooltip sortable="custom"></el-table-column>
                    <el-table-column prop="Rtsp" label="直播源地址" min-width="300" show-overflow-tooltip></el-table-column>
                    <!-- <el-table-column prop="Onvif" label="ONVIF地址" min-width="200" show-overflow-tooltip></el-table-column> -->
                    <el-table-column prop="Transport" label="传输协议" min-width="100" show-overflow-tooltip></el-table-column>
                    <!-- <el-table-column prop="UserName" label="摄像机用户名" min-width="120" show-overflow-tooltip></el-table-column> -->
                    <!-- <el-table-column prop="Password" label="摄像机密码" min-width="100" show-overflow-tooltip></el-table-column> -->

                    <el-table-column align="center" prop="OnDemand" min-width="120" label="按需直播" sortable="custom">
                        <template slot-scope="scope">
                            {{scope.row.OnDemand ? "✓" : "✗"}}
                        </template>
                    </el-table-column>

                    <el-table-column align="center" prop="Audio" min-width="120" label="开启音频" sortable="custom">
                        <template slot-scope="scope">
                            {{scope.row.Audio && scope.row.Audio != "0" ? "✓" : "✗"}}
                        </template>
                    </el-table-column>

                    <el-table-column align="center" min-width="120" v-if="!serverInfo.VersionType || serverInfo.VersionType == '录像版'" prop="Record" label="开启录像" sortable="custom">
                        <template slot-scope="scope">
                            {{getRecordText(scope.row.Record)}}
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div v-if="mode == 'block'">
                <div v-if="!total" class="empty-channels">没有可用配置通道</div>
                <div class="col-sm-6 channel-info" v-for="channel in Channels" :key="channel.Channel">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <div class="panel-title">
                                <span field="Name" class="text-primary ellipsis panel-title-left">{{channel.Name}}</span>
                                <div class="pull-right ellipsis panel-title-right">
                                    <el-switch @change="enableChannel(channel)" v-model="channel.Enable" :active-value="1" :inactive-value="0" style="margin-top:-4px;">
                                    </el-switch>
                                    <button class="btn btn-xs btn-primary" title="配置" style="margin-bottom:5px;margin-left:8px;" @click.prevent="editChannel(channel)"><i class="fa fa-cog" style="font-size:12px"></i></button>
                                </div>
                                <div class="clearfix"></div>
                            </div>
                        </div>
                        <div class="panel-body table-responsive no-padding no-margin" v-loading="channel.bLoading" element-loading-text="加载中">
                            <table class="table table-striped table-condensed" style="white-space:nowrap;font-size:1em;">
                                <tbody>
                                    <tr>
                                        <td>通道号</td>
                                        <td field="Channel">{{channel.Channel}}</td>
                                    </tr>
                                    <tr>
                                        <td>接入类型</td>
                                        <td field="Protocol">{{channel.Protocol}}</td>
                                    </tr>
                                    <tr>
                                        <td>直播源地址</td>
                                        <td field="RTSP">{{channel.Rtsp}}</td>
                                    </tr>
                                    <tr>
                                        <td>ONVIF地址</td>
                                        <td field="ONVIF">{{channel.Onvif}}</td>
                                    </tr>
                                    <tr>
                                        <td>传输协议</td>
                                        <td field="Transport">{{channel.Transport}}</td>
                                    </tr>
                                    <tr>
                                        <td>摄像机用户名</td>
                                        <td field="UserName">{{channel.UserName}}</td>
                                    </tr>
                                    <!-- <tr>
                                        <td>摄像机密码</td>
                                        <td field="Password">{{channel.Password}}</td>
                                    </tr> -->
                                    <tr>
                                        <td>转推CDN地址</td>
                                        <td field="CDN">{{channel.Cdn}}</td>
                                    </tr>
                                    <tr>
                                        <td>叠加文字</td>
                                        <td field="OSD">{{channel.OSD}}</td>
                                    </tr>
                                    <tr>
                                        <td>国标编号</td>
                                        <td field="GBID">{{channel.GBID}}</td>
                                    </tr>
                                    <tr>
                                        <td>按需直播</td>
                                        <td field="OnDemand">{{channel.OnDemand ? "✓" : "✗"}}</td>
                                    </tr>
                                    <tr>
                                        <td>开启音频</td>
                                        <td field="Audio">{{channel.Audio && channel.Audio != "0" ? "✓" : "✗"}}</td>
                                    </tr>
                                    <tr v-if="!serverInfo.VersionType || serverInfo.VersionType == '录像版'">
                                        <td>开启录像</td>
                                        <td field="Record">{{getRecordText(channel.Record)}}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="clearfix"></div>
        <div class="box-footer clearfix" v-if="total > 0">
            <el-pagination class="pull-right" :current-page.sync="currentPage" :page-size="pageSize" :total="total"
                :layout="isMobile() ? 'total,prev,pager,next' : 'total,prev,pager,next,jumper'" :pager-count="isMobile() ? 3 : 5">
            </el-pagination>
        </div>
        <UploadDlg ref="uploadDlg" url="/api/v1/uploadxlsx" @uploaded="uploaded"></UploadDlg>
    </div>
</div>
</template>

<script>
import UploadDlg from "components/UploadDlg.vue";
import ChannelDlg from "components/ChannelDlg.vue";
import "@penggy/jquery.nicescroll";
import _ from 'lodash'
import {
    mapState,
    mapActions
} from "vuex";

export default {
    data() {
        return {
            q: "",
            protocol: "",
            enable: "",
            Channels: [],
            total: 0,
            mode: "list",
            pageSize: 10,
            currentPage: 1,
            sort: 'Channel',
            order: 'ascending',
        };
    },
    components: {
        ChannelDlg,
        UploadDlg
    },
    mounted() {
        // this.$refs["search"].focus();
        // this.getchannels();
        $(document).on('expanded.pushMenu collapsed.pushMenu', this.resizeNiceScroll);
    },
    computed: {
        ...mapState(["serverInfo", "userInfo"])
    },
    methods: {
        modeChange(e) {
            if(this.mode == "block" && e.target.value != "block") {
                this.removeNiceScroll();
            }
            this.mode = e.target.value;
        },
        download() {
            window.open(`/api/v1/downloadxlsx`, "_blank");
        },
        uploaded() {
            this.$message({
                type: 'success',
                message: "上传配置成功！"
            })
            this.getchannels();
            this.$refs['uploadDlg'].hide();
        },
        isMobile() {
            return videojs.browser.IS_IOS || videojs.browser.IS_ANDROID;
        },
        getchannels() {
            $.get("/api/v1/getchannelsconfig", {
                q: this.q,
                protocol: this.protocol,
                enable: this.enable,
                start: this.pageSize * (this.currentPage - 1),
                limit: this.pageSize,
                sort: this.sort,
                order: this.order,
            }).then(data => {
                this.removeNiceScroll();
                this.Channels = (data.LiveQing || data.NVR).Body.Channels;
                this.total = (data.LiveQing || data.NVR).Body.ChannelCount;
                if(!this.isMobile()) {
                    this.$nextTick(() => {
                        $(".channel-info .panel-body").niceScroll({
                            cursorwidth: "10px",
                            cursoropacitymax: 0.5,
                            enablemousewheel: false
                        });
                    });
                }
            })
        },
        sortChange(data) {
            this.sort = data.prop;
            this.order = data.order;
            this.getchannels();
        },
        editChannel(channel) {
            this.$refs["channelDlg"].show(channel);
        },
        enableChannel(channel) {
            this.$set(channel, "bLoading", true);
            $.get("/api/v1/setchannelenable", {
                channel: channel.Channel,
                enable: channel.Enable,
            }).then(data => {
                if ((data.LiveQing || data.NVR).Header.ErrorNum == 200) {
                    this.$message({
                        type: 'success',
                        message: "配置成功！"
                    })
                } else {
                    this.$message({
                        type: "error",
                        message: "配置失败！"
                    })
                }
            }).always(() => {
                this.$delete(channel, "bLoading");
                this.getchannels();
            })
        },
        ready(){
            this.$watch('q', function(newVal, oldVal) {
                this.doDelaySearch();
            });
            this.$watch('enable', function(newVal, oldVal) {
                this.doSearch();
            });
            this.$watch('protocol', function(newVal, oldVal) {
                this.doSearch();
            });
            this.$watch('mode', function(newVal, oldVal) {
                this.doSearch();
            });
            this.$watch('currentPage', function(newVal, oldVal) {
                this.doSearch(newVal);
            });
        },
        doSearch(page = 1) {
            var query = {};
            if(this.q) query["q"] = this.q;
            if(this.enable) query["enable"] = this.enable;
            if(this.protocol) query["protocol"] = this.protocol;
            if(this.mode && this.mode != "list") query["mode"] = this.mode;
            this.$router.replace({
                path: `/channel/${page}`,
                query: query
            });
        },
        doDelaySearch: _.debounce(function() {
            this.doSearch();
        }, 500),
        removeNiceScroll() {
            $(".channel-info .panel-body").getNiceScroll().remove();
        },
        resizeNiceScroll() {
            $(".channel-info .panel-body").getNiceScroll().resize();
        },
        getCommitData(channel) {
            return {
                Channel: channel.Channel,
                Name: channel.Name,
                Enable: channel.Enable,
                Protocol: channel.Protocol,
                RTSP: channel.Rtsp,
                ONVIF: channel.Onvif,
                Username: channel.UserName,
                Password: channel.Password,
                Cdn: channel.Cdn,
                GBID: channel.GBID,
                GBID2: channel.GBID2,
                OnDemand: channel.OnDemand,
                Audio: channel.Audio,
                Record: channel.Record,
                Transport: channel.Transport,
                OSD: channel.OSD,
            }
        },
        getRecordText(rec) {
            if (rec < 0) {
                return "永久保存";
            } else if (rec == 0) {
                return "✗";
            } else if (rec > 0) {
                return `保存${rec}天`;
            }
            return "-";
        }
    },
    beforeRouteEnter(to, from, next) {
        next(vm => {
            vm.q = to.query.q || "";
            vm.enable = to.query.enable || "";
            vm.protocol = to.query.protocol || "";
            vm.mode = to.query.mode || "list";
            vm.pageSize = vm.mode == "block" ? 4 : 10;
            vm.currentPage = parseInt(to.params.page) || 1;
            vm.ready();
        });
    },
    beforeRouteUpdate(to, from, next) {
        this.removeNiceScroll();
        next();
        this.$nextTick(() => {
            this.q = to.query.q || "";
            this.enable = to.query.enable || "";
            this.protocol = to.query.protocol || "";
            this.mode = to.query.mode || "list";
            this.pageSize = this.mode == "block" ? 4 : 10;
            this.currentPage = parseInt(to.params.page) || 1;
            this.getchannels();
        })
    },
    beforeDestroy() {
        this.removeNiceScroll();
        $(document).off('expanded.pushMenu collapsed.pushMenu', this.resizeNiceScroll);
    },
    beforeRouteLeave(to, from, next) {
        this.removeNiceScroll();
        next()
    }
}
</script>

<style lang="less" scoped>
.empty-channels {
    color: #ccc;
    font-weight: bold;
    font-size: 24px;
    text-align: center;
    margin: 150px auto;
}

.channel-info {
    .panel-heading {
        .panel-title {
            position: relative;
            overflow: hidden;

            .panel-title-left {
                position: absolute;
                left: 0;
                right: 100px;
            }
        }
    }
}
</style>
